package com.my.lucky7.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.my.lucky7.common.ApiResult;
import com.my.lucky7.upload.AliyunOSSImageUploader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
@Slf4j
public class FileUploadController {

    // 配置文件存储路径（可根据需要修改）
    private static final String UPLOAD_DIR = "uploads/";

    @Autowired
    private AliyunOSSImageUploader aliyunOSSImageUploader;

    @PostMapping
    public ApiResult uploadImage(
            @RequestParam("image") MultipartFile file,
            @RequestHeader("Authorization") String authorizationHeader) {

        // 1. 验证JWT Token（示例验证逻辑，实际应结合Spring Security）
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            return ApiResult.fail("Missing or invalid Authorization header");
        }

        String token = authorizationHeader.substring(7); // 移除"Bearer "前缀
        // 验证token
        if (!token.equals("901115")) {
            return ApiResult.fail("Missing or invalid Authorization header");
        }

        // 2. 验证文件内容
        if (file.isEmpty()) {
            return ApiResult.fail("Please select an image to upload");
        }

        try {
            String filename = file.getOriginalFilename();
            String uploadImageUrl = aliyunOSSImageUploader.uploadImage(filename, (InputStream) file.getInputStream());
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("uploadImageUrl", uploadImageUrl);
            return ApiResult.success(hashMap);
        } catch (Exception e) {
            log.error("uploadImage error", ExceptionUtil.getMessage(e));
            return ApiResult.fail("Failed to upload image: " + e.getMessage());
        }
    }

    // 生成唯一文件名（防止覆盖）
    private String generateUniqueFileName(String originalName) {
        String ext = originalName.substring(originalName.lastIndexOf("."));
        return UUID.randomUUID() + ext;
    }
}